<template>
  <div class="currentBox">
    <!-- 头部 -->
    <div class="topPart">
      <div class="backBtn" @click="back()"> <svg-icon class-name="back-icon" icon-class="back" /><span>返回</span></div>
      <div class="topMainTitle">会议行为数据分析</div>

      <div class="topRight">
        <span style="margin-right:20px">开始时间：{{ meetingInfo.startTime }}</span>
        <span>结束时间：{{ meetingInfo.endTime }}</span>
      </div>
    </div>
    <!-- 课程信息 -->
    <div class="classBtnLine">
      <div class="classInfoBtn">任务名称：{{ meetingInfo.name }}</div>
      <div class="classInfoBtn">应到人员：{{ meetingInfo.users }}人</div>
    </div>
    <!-- 主要模块(视频+数据) -->
    <div class="mainPart">
      <div class="videoPart">
        <!-- <img :src="imgsrc" alt=""> -->
        <video ref="videoPlayer" width="100%" height="100%" controls muted autoplay />
      </div>
      <div class="dataBox" style="flex:1;width: 200px;">
        <div class="dataBoxTitle"> <img src="../../assets/titleIcon.png" alt="">历史行为数据</div>
        <div class="innerActs" style="flex-direction:row">
          <div class="acitonMeetingBox">
            <div class="actionTitle-meeting">抽烟</div>
            <el-table :data="historySmoke" style="width: 100%" empty-text="暂无数据" :row-class-name="tableRowClass" @row-click="checkVideo">
              <el-table-column prop="time" label="时间" align="center" />
              <el-table-column label="人数" align="center" width="100">
                <template slot-scope="scope">
                  <span style="text-decoration: underline; cursor: pointer;">{{ scope.row.count }}人</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="acitonMeetingBox">
            <div class="actionTitle-meeting">趴桌</div>
            <el-table :data="historyLY" style="width: 100%" empty-text="暂无数据" :row-class-name="tableRowClass" @row-click="checkVideo">
              <el-table-column prop="time" label="时间" align="center" />
              <el-table-column label="人数" align="center" width="100">
                <template slot-scope="scope">
                  <span style="text-decoration: underline; cursor: pointer;">{{ scope.row.count }}人</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="acitonMeetingBox">
            <div class="actionTitle-meeting">玩手机</div>
            <el-table :data="historyPhone" style="width: 100%" empty-text="暂无数据" :row-class-name="tableRowClass" @row-click="checkVideo">
              <el-table-column prop="time" label="时间" align="center" />
              <el-table-column label="人数" align="center" width="100">
                <template slot-scope="scope">
                  <span style="text-decoration: underline; cursor: pointer;">{{ scope.row.count }}人</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <!-- 考勤统计 -->
      <div class="dataBox" style="width: 276px;">
        <div class="dataBoxTitle"> <img src="../../assets/titleIcon.png" alt="">出勤率</div>
        <div class="innerActs">
          <div class="inThreeTitle">人头数统计</div>
          <div class="inThree">
            <div class="inThree-In"><div>{{ attendNum }}<i>人</i></div><span>实到数</span></div>
            <div class="inThree-In"><div>{{ meetingInfo.users }}<i>人</i></div><span>应到数</span></div>
            <div class="inThree-In"><div>{{ Percent(attendNum,meetingInfo.users) }}<i>%</i></div><span>实到率</span></div>
          </div>
          <div class="inThreeTitle">精细化考勤</div>
          <div class="inThree">
            <div class="inThree-In"><div>{{ recognizeNum }}<i>人</i></div><span>识别数</span></div>
            <div class="inThree-In"><div>{{ meetingInfo.users }}<i>人</i></div><span>总人数</span></div>
            <div class="inThree-In"><div>{{ Percent(recognizeNum,meetingInfo.users) }}<i>%</i></div><span>识别率</span></div>
          </div>
        </div>
        <!-- 按钮 -->
        <el-button type="primary" style="    width: 200px; margin: 0 auto 10px;" @click="checkPerson()">考勤详情</el-button>
        <!-- 人脸考勤详情弹窗 -->
        <el-dialog title="人脸考勤详情" :visible.sync="facesDialog" width="80%" class="faceBox" @close="closeFaces()">
          <div class="openFrame">
            <div class="openFrame-left">
              <div class="openFrame-box-title">识别名单</div>
              <div class="openFrame-box" style="height:368px;margin-bottom:20px">
                <div v-for="(item,index) in recognized" :key="index" class="onePerson">
                  <div class="onePerson-img"><img :src="photoUrl(item.photo)"></div>
                  <div class="onePerson-name">{{ item.username }}</div>
                </div>
              </div>
              <div class="openFrame-box-title">未识别名单</div>
              <div class="openFrame-box" style="height:244px">
                <div v-for="item in noRecognized" :key="item.phone" class="onePerson">
                  <div class="onePerson-img"><img :src="photoUrl(item.photo)"></div>
                  <div class="onePerson-name">{{ item.username }}</div>
                </div>
              </div>
            </div>
            <div class="openFrame-right">
              <div class="right-one">
                <div>总人数：<span>{{ meetingInfo.users }}</span></div>
                <div>实到人数：<span>{{ attendNum }}</span></div>
                <div>识别人数：<span>{{ recognizeNum }}</span></div>
              </div>
              <div class="right-two">
                <circleChart2 :data="dataA" :title="title1" :set="chartSet" />
              </div>
              <div class="right-two">
                <circleChart2 :data="dataB" :title="title2" :set="chartSet" />
              </div>

            </div>

          </div>
        </el-dialog>
      </div>

    </div>
    <!-- 数据分析 -->
    <div class="analysisPart">
      <div class="dataBox dataBoxWidth3" style="margin-left:0px;">
        <div class="dataBoxTitle"> <img src="../../assets/titleIcon.png" alt="">行为占比</div>
        <circleChart v-if="showCircle" :circle-data="circleData" />
      </div>
      <div class="dataBox dataBoxWidth3">
        <div class="dataBoxTitle"> <img src="../../assets/titleIcon.png" alt="">抽烟趋势</div>
        <lineChart v-if="showChart1" :line-color="lineColor1" :data="smokeData" :grid-set="gridSet" />
      </div>
      <div class="dataBox dataBoxWidth3">
        <div class="dataBoxTitle"> <img src="../../assets/titleIcon.png" alt="">趴桌趋势</div>
        <lineChart v-if="showChart1" :line-color="lineColor2" :data="LYData" :grid-set="gridSet" />
      </div>
      <div class="dataBox dataBoxWidth3">
        <div class="dataBoxTitle"> <img src="../../assets/titleIcon.png" alt="">玩手机趋势</div>
        <lineChart v-if="showChart1" :line-color="lineColor3" :data="phoneData" :grid-set="gridSet" />
      </div>
    </div>
  </div>
</template>

<script>
import lineChart from './charts/lineChart2.vue'
import circleChart from './charts/circleChart.vue'
import circleChart2 from './charts/circleChart2.vue'
import Hls from 'hls.js'

// 接口
import { getMeetingAnalysisData, getTaskDataById } from '@/api/main'

export default {
  name: 'MeetingAnalysis',
  components: { lineChart, circleChart, circleChart2 },
  data() {
    return {
      hls: null, // HLS 实例
      jumpTime: 0, // 用户输入的时间
      meetingInfo: {
        name: '',
        users: null,
        startTime: null,
        endTime: null
      },
      id: null,
      total: 45,
      imgsrc: require('../../assets/img001.png'),
      length: null,
      gridSet: {
        max: null,
        interval: null
      },

      smokeData: [], // 抽烟数据
      LYData: [], // 趴桌数据
      phoneData: [], // 玩手机

      showChart1: false, // 显示
      showChart2: false, // 显示
      showChart3: false, // 显示

      historySmoke: [],
      historyLY: [],
      historyPhone: [],

      lineColor1: '#ffee34',
      lineColor2: '#8cff59',
      lineColor3: '#7ea5ff',

      circleData: {}, // 饼图数据
      showCircle: false,

      usersItems: [], // 所有参会人员
      attendanceIds: [], // 已识别的人员的id

      attendNum: null, // 实到人数
      recognizeNum: null, // 识别人数
      facesDialog: false,
      recognized: [], // 已识别出的人员list
      noRecognized: [], // 未识别名单
      title1: '出勤统计',
      title2: '识别统计',
      dataA: [],
      dataB: [],
      chartSet: {
        titleColor: '#333'
      }
    }
  },
  computed: {

  },
  watch: {
    '$route.query.id': {
      immediate: true,
      handler(newId) {
        if (newId) {
          setTimeout(() => this.playVideo(), 100) // 避免 ref 还没渲染完成
        }
      }
    }
  },
  created() {
    // 获取query缓存
    this.setQuery()
    // 获取会议的数据
    this.getDataForMeeting()
    // 通过id获取任务信息
    this.getMeetingInfo()
  },
  beforeDestroy() {

  },
  mounted() {
    this.$nextTick(() => this.playVideo())
  },
  methods: {
    getMeetingInfo() {
      const id = this.$route.query.id
      getTaskDataById(id).then(response => {
        this.meetingInfo.name = response.data.task_data.name
        this.meetingInfo.users = response.data.task_users.length
        this.meetingInfo.startTime = response.data.task_data.start_time.replace('T', ' ')
        this.meetingInfo.endTime = response.data.task_data.end_time.replace('T', ' ')
        // 所有参会人员信息
        this.usersItems = response.data.task_users
      })
    },
    // 设置缓存
    setQuery() {
      const params = this.$route.query
      if (Object.keys(params).length === 0) {
        const savedParams = JSON.parse(localStorage.getItem('queryParams'))
        if (savedParams) {
          this.$router.replace({ query: savedParams })
        }
      } else {
        localStorage.setItem('queryParams', JSON.stringify(params))
      }
    },

    back() {
      // this.$router.back()
      this.$router.push({ path: '/meetingList' })
    },

    // 播放视频
    playVideo() {
      const videoElement = this.$refs.videoPlayer
      if (!videoElement) {
        console.error('Video element not found')
        return
      }

      const id = this.$route.query.id
      if (!id) {
        console.error('播放视频失败：id 为空')
        return
      }

      const url = this.$VIDEO_URL + '/' + id + '/' + id + '.m3u8'
      
      if (Hls.isSupported()) {
        this.hls = new Hls()
        this.hls.loadSource(url)
        this.hls.attachMedia(videoElement)
        this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
          videoElement.play()
        })
      } else if (videoElement.canPlayType('application/vnd.apple.mpegurl')) {
        videoElement.src = url
        videoElement.load()
        videoElement.muted = true
        videoElement.play()
      } else {
        console.error('当前浏览器不支持 HLS 播放')
      }
    },

    // **跳转到指定时间**
    seekToTime(time) {
      const videoElement = this.$refs.videoPlayer
      if (videoElement) {
        videoElement.currentTime = time
        // console.log(`跳转到 ${time} 秒`)
      } else {
        console.error('Video element not found')
      }
    },

    // 查看当前时间点的视频
    checkVideo(row) {
      // console.log('点击的行数据:', row)
      const time = row.seconds
      this.seekToTime(time)
    },

    // 百分比
    Percent(e, total) {
      if (total > 0 && e > 0) {
        const num = (e / total) * 100
        return Number(num.toFixed(1))
      } else {
        return 0
      }
    },
    // 获取会议数据
    getDataForMeeting() {
      const id = this.$route.query.id
      getMeetingAnalysisData(id).then(response => {
        // 所有已识别人员的id
        this.attendanceIds = response.data.attendance_data.slice(1)
        // 如果是 ['']，则将其赋值为 []
        if (this.attendanceIds.length === 1 && this.attendanceIds[0] === '') {
          this.attendanceIds = []
        }
        // console.log('--------所有已识别人员的id', this.attendanceIds)
        // 实到人数和识别数
        const data = response.data.attendance_data
        // let data = JSON.parse(dataA);
        // console.log('--------会议数据', response.data)
        // 处理数据为空数组的情况
        if (data.length === 0) {
          this.attendNum = 0
          this.recognizeNum = 0
        } else {
          // 处理第一个数
          this.attendNum = (data[0] === '' || data[0] === '0') ? 0 : data[0]
          // 处理第二个数
          this.recognizeNum = (data[1] === '' || data[1] === '0') ? 0 : data.length - 1
        }

        // 取出三个行为的数据
        this.circleData = [
          { value: response.data.cnt_smoking, name: '抽烟' },
          { value: response.data.cnt_ly, name: '趴桌' },
          { value: response.data.cnt_phone, name: '玩手机' }
        ]
        this.showCircle = true

        // 取出时长
        const duration = response.data.duration
        this.setChartGrid(duration)// 计算表格宽度

        // 抽烟数据
        this.smokeData = response.data.data_smoking
        this.showChart1 = true
        // 历史抽烟数据
        this.historySmoke = (this.smokeData || []).map(item => {
          const addSeconds = item[0] // 第一个项是秒数
          const count = item[1] // 第二个项是count
          // 使用基准时间加上秒数计算新的时间
          const newTime = this.timeAdd(this.meetingInfo.startTime, addSeconds)
          return { time: newTime, count: count, seconds: addSeconds }
        })

        // 趴桌数据
        this.LYData = response.data.data_ly
        this.showChart2 = true
        // 历史趴桌数据
        this.historyLY = (this.LYData || []).map(item => {
          const addSeconds = item[0] // 第一个项是秒数
          const count = item[1] // 第二个项是count
          // 使用基准时间加上秒数计算新的时间
          const newTime = this.timeAdd(this.meetingInfo.startTime, addSeconds)
          return { time: newTime, count: count, seconds: addSeconds }
        })

        // 玩手机数据
        this.phoneData = response.data.data_phone
        this.showChart3 = true
        // 历史玩手机数据
        this.historyPhone = (this.phoneData || []).map(item => {
          const addSeconds = item[0] // 第一个项是秒数
          const count = item[1] // 第二个项是count
          // 使用基准时间加上秒数计算新的时间
          const newTime = this.timeAdd(this.meetingInfo.startTime, addSeconds)
          return { time: newTime, count: count, seconds: addSeconds }
        })
      })
    },

    // 时间相加
    timeAdd(timeString, addSeconds) {
      // 创建一个新的 Date 对象
      const date = new Date(timeString)
      // 加上秒数
      date.setSeconds(date.getSeconds() + addSeconds)
      // 获取本地时间的年、月、日、时、分、秒
      const year = date.getFullYear()
      const month = date.getMonth() + 1 // 注意月份从 0 开始
      const day = date.getDate()
      const hours = date.getHours()
      const minutes = date.getMinutes()
      const seconds = date.getSeconds()
      // 自定义输出格式，移除 T，使用 - 分隔
      return `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    },

    // 图表x长度设置
    setChartGrid(length) {
      if (length <= 900) {
        this.gridSet.max = 900
        this.gridSet.interval = 60
      } else if (length > 900 && length <= 1800) {
        this.gridSet.max = 1800
        this.gridSet.interval = 120
      } else if (length > 1800 && length <= 2700) {
        this.gridSet.max = 2700
        this.gridSet.interval = 180
      } else if (length > 2700 && length <= 3600) {
        this.gridSet.max = 3600
        this.gridSet.interval = 300
      } else {
        const roundNum = Math.ceil(length / 50)
        this.gridSet.max = roundNum * 50
        this.gridSet.interval = (roundNum * 50) / 10
      }
    },

    // 精细化考勤弹窗
    checkPerson() {
      this.facesDialog = true
      // 筛选赋值
      // A已识别出的人的id---this.attendanceIds
      // B所有人员---this.usersInfo
      var arr1 = this.usersItems
      var arr2 = this.attendanceIds

      for (var i = 0; i < arr1.length; i++) {
        var id1 = arr1[i].id
        // var isDifferent = false;
        for (var j = 0; j < arr2.length; j++) {
          var id2 = arr2[j]
          if (id1 === id2) {
            this.recognized.push(arr1[i]) // 这是相同的值
            break
          }
        }
      }
      // 从所有人员总减去已识别出来的人
      // 从arr1中减去arr2中包含的元素
      this.noRecognized = arr1.filter(item => !this.recognized.includes(item))

      // 传递图表数据
      const tatalNum = this.meetingInfo.users// 总人数
      const actualNum = this.attendNum// 实到人数
      const actualNumNone = tatalNum - actualNum// 未到人数
      const attentNum = this.recognizeNum// 识别人数
      const attentNumNone = tatalNum - attentNum// 未识别人数

      // 出勤率
      this.dataA = [
        { value: actualNum, name: '出勤数' },
        { value: actualNumNone, name: '缺勤数' }
      ]
      // 识别率
      this.dataB = [
        { value: attentNum, name: '识别数' },
        { value: attentNumNone, name: '未识别' }
      ]
    },

    // 关闭人脸识别详情
    closeFaces() {
      this.facesDialog = false
      this.recognized = []
      this.noRecognized = []
    },
    // 照片地址转换
    photoUrl(e) {
      return this.$API_BASE_URL + '/upload/' + e
    },

    // 表格样式
    tableRowClass() {
      return 'rowClass'
    }

  }
}
</script>

<style>
/* 定义滚动条的宽度和背景颜色 */
.acitonMeetingBox ::-webkit-scrollbar {
  width: 10px;
  background-color: rgba(255,255,255,0.03);
  }

/* 定义滑块的样式，包括圆角和内阴影 */
.acitonMeetingBox ::-webkit-scrollbar-thumb {
  border-radius: 10px;
  -webkit-box-shadow:none;
  background-color:  rgba(255,255,255,0.1);
}
.rowClass{
  cursor: pointer;
}

</style>
